<template>
  <div class="nav-page">
    <div class="container-card">
      <section class="card">
        <header class="card-header">
          <div class="title">{{ paper?.name || '试卷详情' }}</div>
          <div class="ops">
            <el-button size="small" @click="goBack">返回</el-button>
          </div>
        </header>
        <div class="card-body">
          <div class="paper-meta" v-if="paper">
            <span>时长：{{ paper.durationMinutes }} 分钟</span>
            <span>总分：{{ paper.totalScore }}</span>
            <span>及格线：{{ paper.passScore }}</span>
          </div>

          <div v-loading="loading" class="question-list">
            <div v-for="(item, index) in questionItems" :key="item.id || index" class="question-card">
              <!-- 第一行：题型 + 题干 + 正确答案 + 删除按钮 -->
              <div class="question-header">
                <div class="question-info">
                  <span class="question-index">{{ index + 1 }}.</span>
                  <span class="question-stem">{{ item.question.stem }}</span>
                  <el-tag :type="typeTagType(item.question.questionType)" size="small" class="type-tag">
                    {{ typeText(item.question.questionType) }}
                  </el-tag>
                  <span class="correct-answer">正确答案: {{ getCorrectAnswer(item) }}</span>
                </div>
                <el-button type="danger" size="small" :icon="Delete" @click="deleteQuestion(item, index)"
                  class="delete-btn">
                  删除
                </el-button>
              </div>

              <!-- 第二行：选项 -->
              <div class="question-options" v-if="hasOptions(item)">
                <div class="opt-list" :class="isShortOptions(item.options) ? 'opt-short' : 'opt-long'">
                  <div v-for="(opt, idx) in normalizeOptions(item.options)" :key="idx" class="opt-item"
                    :class="{ 'correct': isCorrectOption(item, idx) }">
                    <span class="opt-index">{{ indexLabel(idx) }}</span>
                    <span class="opt-text">{{ optionText(opt) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="questionItems.length === 0 && !loading" class="empty-state">
              暂无题目数据
            </div>
          </div>
        </div>
      </section>
    </div>
  </div>

</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { getPaperDetail, deletePaperQuestionByPaper, getQuestionDetail, deletePaperQuestion } from '@/api/exam/exam'

const route = useRoute()
const router = useRouter()
const paperId = Number(route.params.id)

const paper = ref<any | null>(null)
const loading = ref(false)
const questionItems = ref<any[]>([])

function typeText(t?: number) {
  return t === 1 ? '单选' : t === 2 ? '多选' : t === 3 ? '判断' : t === 4 ? '填空' : '-'
}
function typeTagType(t?: number) {
  return t === 1 ? 'success' : t === 2 ? 'warning' : t === 3 ? 'info' : t === 4 ? 'primary' : 'default'
}

async function loadDetail() {
  loading.value = true
  try {
    const paperRes = await getPaperDetail(paperId)
    console.log('paperRes', paperRes)

    // 修正数据访问路径
    if (paperRes.data && paperRes.data.code === 0) {
      paper.value = paperRes.data.data.paper
      questionItems.value = paperRes.data.data.items
    } else {
      throw new Error('接口返回数据格式错误')
    }

    console.log('questionItems', questionItems.value)
  } catch (e) {
    console.error('加载试卷详情失败:', e)
    ElMessage.error('加载试卷详情失败')
  } finally {
    loading.value = false
  }
}

function goBack() {
  router.back()
}

onMounted(loadDetail)

// —— 选项显示相关 ——
function optionText(o: any): string {
  if (o == null) return ''
  if (typeof o === 'string') return o
  // 优先使用content字段，兼容其他字段名
  return (
    o.content ?? o.text ?? o.label ?? o.value ?? (typeof o === 'object' ? JSON.stringify(o) : String(o))
  )
}

function normalizeOptions(opts: any): any[] {
  return Array.isArray(opts) ? opts : []
}

function isShortOptions(opts: any): boolean {
  const arr = normalizeOptions(opts)
  if (arr.length !== 4) return false
  const threshold = 12 // 字数阈值，可按需要调整
  return arr.every((o) => optionText(o).length <= threshold)
}

function indexLabel(idx: number): string {
  const map = ['A', 'B', 'C', 'D', 'E', 'F']
  return map[idx] ?? String(idx + 1)
}

// 获取正确答案显示文本
function getCorrectAnswer(item: any): string {
  if (!item.options || !Array.isArray(item.options)) return '未设置'

  const correctOptions = item.options.filter((opt: any) => opt.isCorrect === 1)

  if (correctOptions.length === 0) return '未设置'

  if (item.question.questionType === 1) { // 单选
    return correctOptions[0].optionKey
  } else if (item.question.questionType === 2) { // 多选
    return correctOptions.map((opt: any) => opt.optionKey).join(', ')
  } else if (item.question.questionType === 3) { // 判断
    // 判断题通常是正确/错误，根据optionKey判断
    const correctKey = correctOptions[0].optionKey
    return correctKey === 'A' ? '正确' : '错误'
  } else if (item.question.questionType === 4) { // 填空
    return correctOptions.map((opt: any) => opt.content).join(', ')
  }

  return correctOptions.map((opt: any) => opt.optionKey).join(', ')
}

// 判断是否有选项
function hasOptions(item: any): boolean {
  return item.question.questionType <= 3 && Array.isArray(item.options) && item.options.length > 0
}

// 判断选项是否为正确答案
function isCorrectOption(item: any, optionIndex: number): boolean {
  if (!item.options || !Array.isArray(item.options)) return false

  const option = item.options[optionIndex]
  return option && option.isCorrect === 1
}

// 删除题目
async function deleteQuestion(item: any, index: number) {
  try {
    await ElMessageBox.confirm(
      `确定要删除题目"${item.question.stem?.substring(0, 20)}..."吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用删除API
    await deletePaperQuestionByPaper(paperId, item.question.id)

    // 从列表中移除
    questionItems.value.splice(index, 1)

    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style scoped>
.nav-page {
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  background: #f5f7fb;
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: flex-start;
  /* 不做垂直居中 */
  padding-top: 20px;
  /* 距离顶部 100 */
  padding-bottom: 20px;
  /* 距离底部 100 */
}

.container-card {
  height: 95vh;
  min-width: 900px;
  max-width: 1260px;
  margin: 0 auto;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 20px;
  box-shadow: 0 10px 24px rgba(31, 45, 61, 0.06);
  padding-top: 20px;
  padding-bottom: 24px;
  padding-left: 60px;
  /* 保持左右留白，不顶格 */
  padding-right: 60px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 6px 12px 6px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header .title {
  font-weight: 600;
}

.card-header .ops {
  display: flex;
  gap: 8px;
  align-items: center;
}

.card-body {
  padding-top: 12px;
}

.paper-meta {
  display: flex;
  gap: 12px;
  color: #666;
  margin-bottom: 10px;
}

/* —— 题目列表样式 —— */
.question-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.question-card {
  border: none;
  border-radius: 0;
  padding: 8px 0;
  background: transparent;
  box-shadow: none;
  transition: none;
}

.question-card:hover {
  box-shadow: none;
}

.question-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 3px;
}

.question-info {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
}

.type-tag {
  flex-shrink: 0;
}

.question-stem {
  color: #1f2937;
  font-weight: 500;
  line-height: 1.5;
}

.question-index {
  color: #374151;
  font-weight: 600;
  margin: 0 6px 0 8px;
}

.correct-answer {
  color: #059669;
  font-size: 14px;
  font-weight: 500;
  flex-shrink: 0;
  background: #ecfdf5;
  padding: 4px 8px;
  border-radius: 6px;
}

.delete-btn {
  flex-shrink: 0;
}

.question-options {
  margin-left: 8px;
  margin-top: 1px;
}

.empty-state {
  text-align: center;
  color: #6b7280;
  padding: 40px 20px;
  font-size: 16px;
}

.opt-list {
  display: grid;
  gap: 8px;
}

.opt-short {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

.opt-long {
  grid-template-columns: 1fr;
}

.opt-item {
  border: none;
  border-radius: 0;
  padding: 4px 0;
  background: transparent;
  display: flex;
  gap: 8px;
  align-items: flex-start;
  transition: all 0.2s ease;
}

.opt-item.correct {
  border-color: transparent;
  background: transparent;
}

.opt-item.correct .opt-index {
  color: #059669;
}

.opt-item.correct .opt-text {
  color: #065f46;
}

.opt-index {
  font-weight: 600;
  color: #4b5563;
}

.opt-text {
  color: #1f2937;
  word-break: break-word;
}

@media (max-width: 720px) {
  .container-card {
    padding-left: 16px;
    padding-right: 16px;
  }

  .opt-short {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>
